home *** CD-ROM | disk | FTP | other *** search
- Path: news1.interserv.net!news
- From: <102276.2374@compuserv.com>
- Newsgroups: comp.lang.c++
- Subject: const member function
- Date: 10 Apr 1996 09:23:43 GMT
- Organization: InterServ News Service
- Message-ID: <4kfumv$1sp@lal.interserv.net>
- NNTP-Posting-Host: ad57-200.compuserve.com
- Content-Type: text/plain
- Content-length: 1196
- X-Newsreader: AIR Mosaic (32-bit) 4.00
-
-
- >class X
- >{
- >public: // Public methods
- > X( ) : _value( 0 ) { }
- > X( int value ) : _value( value ) { }
- >
- > int value( ) const { return _value; }
- >
- >private: // Private methods
- >
- > int& value( ) { return _value; }
- >
- >private: // Private data members
- > int _value;
- >};
- >
- >main( )
- >{
- > X t1( 1 );
- > const X t2( 2 );
- >
- > cout << t1.value() << endl; // This is an error
- >
- > // This line
- > cout << t2.value() << endl; // Does this work?
- >}
- >
-
- Sounds to me like your compilers are overloading the value() function
- based on the constness of whatever object your are using to invoke the
- method.
-
- Obviously, the following declaration results in a non-const object :
-
- X t1(1);
-
- Since this is a non-const object, I believe that the compiler is attempting
- to invoke the non-const value() function in your class.
-
- Since this function is declared as private, only members, derived classes
- and freinds would have access to it.
-
- To prove this, you could try making istream::operator<<(int) a friend to see
- if the example code will compile.
-
- Please let me know if this works.
-
- David Visage
- 102276.2374@compuserv.com
-
-
-